<template>
  <div ref="searchRef" style="min-height: 56px">
    <a-form :model="formState" :label-col="{ style: `width:${labelWidth}px` }" >
      <a-row v-for="(o, i) in formCol" :key="`search-form-${i}`" :gutter="20">
        <a-col v-for="(t, j) in o" :key="`search-item-${j}`" :span="24 / col">
          <a-form-item
            :label="t.name"
            :label-col="t.labelCol"
            :wrapper-col="t.wrapperCol"
          >
            <a-input
              v-if="t.type === 'input'"
              v-model:value="formState[t.filed]"
              :placeholder="t.placeholder"
              v-bind="{ ...t.attrs }"
            ></a-input>
            <a-input-group
              v-if="t.type === 'inputGroup'"
              style="display: flex"
              compact
              :placeholder="t.placeholder"
              :options="t.list"
              v-bind="{ ...t.attrs }"
            >
              <a-select
                v-model:value="formState[t.filed[0]]"
                style="width: 60px; margin-right: 5px"
              >
                <a-select-option value="0">{{ "&lt;" }}</a-select-option>
                <a-select-option value="1">=</a-select-option>
                <a-select-option value="2">></a-select-option>
              </a-select>
              <a-input v-model:value="formState[t.filed[1]]" style="flex: 1" />
            </a-input-group>
            <a-input-group
              v-if="t.type === 'time-picker'"
              compact
              :placeholder="t.placeholder"
              :options="t.list"
              v-bind="{ ...t.attrs }"
            >
              <a-time-picker
                v-model:value="formState[t.filed[0]]"
                style="width: 50%"
                value-format="HH:mm:ss"
              />
              <a-time-picker
                v-model:value="formState[t.filed[1]]"
                style="width: 50%"
                value-format="HH:mm:ss"
              />
            </a-input-group>
            <a-select
              v-if="t.type === 'select'"
              v-model:value="formState[t.filed]"
              :placeholder="t.placeholder"
              :options="t.list"
              :allow-clear="true"
              :filter-option="filterOption"
              v-bind="{ ...t.attrs }"
              @change="t?.attrs?.change"
            ></a-select>
            <a-cascader
              v-if="t.type === 'cascader'"
              v-model:value="formState[t.filed]"
              :placeholder="t.placeholder"
              :options="t.list"
              :allow-clear="true"
              v-bind="{ ...t.attrs }"
            ></a-cascader>
            <a-range-picker
              v-if="t.type === 'range-picker'"
              v-model:value="formState[t.filed]"
              v-bind="{ ...t.attrs }"
              style="width: 100%"
              @change="t?.attrs?.change"
            ></a-range-picker>
            <a-date-picker
              v-if="t.type === 'date-picker'"
              v-model:value="formState[t.filed]"
              style="width: 100%"
              v-bind="{ ...t.attrs }"
              @change="t.attrs?.change"
            />
            <a-month-picker
              v-if="t.type === 'month-picker'"
              v-model:value="formState[t.filed]"
              style="width: 100%"
              v-bind="{ ...t.attrs }"
              @change="t?.attrs?.change"
            />
            <a-tree-select
              v-if="t.type === 'tree-select'"
              v-model:value="formState[t.filed]"
              :placeholder="t.placeholder"
              style="width: 100%"
              v-bind="{ ...t.attrs }"
            />
            <slot
              v-if="t.type === 'slot'"
              :name="t.filed"
              :record="formState"
            ></slot>
          </a-form-item>
        </a-col>
        <a-col v-if="o.length != col" :span="(24 / col) * (col - o.length)">
          <a-form-item>
            <div class="btn-box">
              <a-space :size="10">
                <a-button @click="onReset">重置</a-button>
                <a-button type="primary"  @click="onQuery">查询</a-button>
              </a-space>
              <div v-if="needShrink" class="shrink-box">
                <div @click="onChangeShrink">
                  <DownOutlined v-if="shrink" />
                  <UpOutlined v-else />
                  {{ shrink ? "展开" : "收起" }}
                </div>
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script setup name="FormSearch">
import { debounce } from "@/utils/common";
import moment from "moment";
import dayjs from "dayjs";
// 仓库数据
import { useStoreApp } from "@/store";
const storeApp = useStoreApp();
// const queryOptions = [
//   { name: '创建日期', type: 'range-picker', value: [], placeholder: '请选择', filed: 'rangeDate',
//     attrs: { format: 'YYYY-MM-DD' }
//   },
//   { name: '角色', type: 'select', value: '', placeholder: '请选择', filed: 'roleId',
//     list: [],
//     async: async (data: any) => {
//       await postAllRole().then((result:any) => {
//         if (result.code === 2000) {
//           data.list = filedArrJoin(result.data, 'name', 'id');
//         }
//       });
//     }
//   },
//   { name: '绑定手机', type: 'input', value: '', placeholder: '请选择', filed: 'phoneNumber' },
//   { name: '登录账号/姓名', type: 'input', value: '', placeholder: '请选择', filed: 'userName' },
//   { name: '状态', type: 'select', value: '', placeholder: '请选择', filed: 'status', list: [] },
// ];
const props = defineProps({
  options: {
    type: Array,
    default: () => [],
  },
  // 默认70显示4个字符，增加或减少一个字符以15递增或递减
  labelWidth: {
    type: Number,
    default: 70,
  },
  // 列宽，配合ui宽度
  colWidth: {
    type: Number,
    default: 350,
  },
});
const emit = defineEmits(["ok", "reset"]);

const searchRef = ref(null);
const wBox = ref(0);
// 一行列数
const col = ref(0);
// 行集合
const formCol = ref([]);
// 是否需要收缩
const needShrink = ref(false);
// 收缩状态
const shrink = ref(true);
const formState = ref({});
// 一列宽度
const itemWidth = ref(0);
// 计算表单的宽度
// const formWidth = computed(() => itemWidth.value - props.labelWidth - 30);

const handle = debounce(function () {
  shrink.value = window.innerHeight < 1080;
  storeApp.saveShrink(shrink.value);
  if (searchRef.value) {
    wBox.value = searchRef.value.clientWidth;
  }
  // 计算一行个数
  col.value = Math.floor(wBox.value / props.colWidth);
  // 一行最多4个，方便计算
  col.value = col.value > 4 ? 4 : col.value;
  // 计算一列的宽度
  itemWidth.value = Math.floor(wBox.value / col.value);
  count();
}, 300);

const count = () => {
  formCol.value = [];
  // 判断有多少行
  let len = Math.ceil(props.options.length / col.value);
  // 在+上查询按钮列的情况下，判断有多少行
  let minLen = Math.ceil((props.options.length + 1) / col.value);
  // 克隆一份原数据
  let cloneOptions = [].concat(props.options);
  // 判断是否需要有展开的按钮
  needShrink.value = minLen > 1;
  // 如果表单查询个数等于或者大于一行的最大个数和收缩为true的情况下直接截取一行的最大个数-1的数组长度，因为后面要拼一个查询列
  if (props.options.length >= col.value && shrink.value) {
    formCol.value.push(cloneOptions.splice(0, col.value - 1));
  } else {
    // 如果是展开的话就直接历编最大列数
    // 防止col.value为0时 len为无限大数Infinity 死循环
    while (Number.isFinite(len) && len > 0) {
      // eslint-disable-next-line vue/no-mutating-props
      if (len === 1) {
        formCol.value.push(cloneOptions);
        // 当最后一行的个数等于最大个数时要新增一行用于查询列
        if (cloneOptions.length === col.value) {
          formCol.value.push([]);
        }
      } else {
        // 直接截取表单进一行
        formCol.value.push(cloneOptions.splice(0, col.value));
      }
      len--;
    }
  }
};
// watch(() => props.options, ()=>{
//   // 特殊 告警类型重新选择时，告警事件需清空
//   props.options.forEach(o => {
//     if (o?.attrs?.isEventType) {
//       formState.value[o.filed] = o.value;
//     }
//   });
// }, {
//   deep: true,
// });

// 选择框搜索过滤
const filterOption = (value, option) => {
  return option.label.indexOf(value) >= 0;
};

onMounted(() => {
  window.addEventListener("resize", handle);
  // shrink.value = window.innerHeight < 1080;
  // storeApp.saveShrink(shrink.value);
  // 历编表单赋值
  props.options.forEach(async (o) => {
    if (Array.isArray(o.filed)) {
      o.filed.map((item, index) => {
        formState.value[item] = o.value[index];
      });
    } else {
      formState.value[o.filed] = o.value;
    }
    // 如果是列表并且是异步数据，需要回调赋值
    if (["select", "tree-select", "cascader"].includes(o.type) && o.async) {
      console.log("async------------");
      await o.async(o);
      console.log("async+++++++++++++");
    }
  });
  handle();
});
// 一行最大个数改变时重新触发计算
watch(
  () => col.value,
  () => {
    count();
  }
);
// 收缩伸展触发重新计算
const onChangeShrink = () => {
  shrink.value = !shrink.value;
  storeApp.saveShrink(shrink.value);
  console.log("shrink.value", shrink.value);
  count();
};

// 日期类型数据处理
const dateHandle = (item, dateMsg) => {
  if (item.type == "range-picker") {
    // dateFields 日期起始与终止数组 [start,end]
    for (let key in item.dateFields) {
      dateMsg[item.dateFields[key]] =
        !formState.value[item.filed] || !formState.value[item.filed][key]
          ? null
          : key == "0"
          ? dayjs(formState.value[item.filed][key])
              .startOf("day")
              .format("YYYY-MM-DD HH:mm:ss")
          : dayjs(formState.value[item.filed][key])
              .endOf("day")
              .format("YYYY-MM-DD HH:mm:ss");
    }
    console.log("dateMsg", dateMsg);
  }
};
// 特殊字段处理
const specialFieldHandle = (item, dateMsg) => {
  if (item.fieldHandle && typeof item.fieldHandle === "function") {
    item.fieldHandle(formState.value[item.filed] || null, dateMsg);
  }
};

const onQuery = () => {
  console.log(33);
  let dateMsg = {};
  let specialFieldMsg = {};
  props.options.map((item) => {
    dateHandle(item, dateMsg);
    specialFieldHandle(item, specialFieldMsg);
  });

  emit("ok", { ...formState.value, ...dateMsg, ...specialFieldMsg });
};

const onReset = () => {
  const dateMsg = onResetFormState();
  const params = { ...formState.value, ...dateMsg };
  emit("reset", params);
  setTimeout(() => emit("ok", params), 0);
};

const onResetFormState = () => {
  let data = {};
  props.options.forEach((o) => {
    if (Array.isArray(o.filed)) {
      o.filed.map((item, index) => {
        formState.value[item] = o.value[index];
      });
    } else {
      formState.value[o.filed] = o.value;
    }

    dateHandle(o, data);
    specialFieldHandle(o, data);
  });
  return data;
};
defineExpose({
  onQuery,
  onReset,
  onResetFormState,
  formState,
});
</script>

<style scoped lang="less">
.btn-box {
  display: flex;
  justify-content: flex-end;
  > .shrink-box {
    display: flex;
    align-items: center;
    width: 60px;
    margin-left: 10px;
    > div {
      // color: rgb(224, 111, 31);
      cursor: pointer;
    }
  }
}
.shrink {
  align-items: flex-end;
  margin-bottom: 20px;
}

:deep(.ant-form-item) {
  width: 100%;
}
:deep(.ant-form-item-control-input) {
  margin-right: 30px;
}
:deep(.ant-col) {
  &:last-child .ant-form-item-control-input {
    margin-right: 0;
  }
}

input[type="number"] {
  -moz-appearance: textfield;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
// :deep(.ant-form-item-label) {
//   text-align-last: justify;
//   padding-right: 5px;
//   position: relative;
//   &::after {
//     content: ':';
//     position: absolute;
//     top: 50%;
//     transform: translateY(-50%);
//     right: 5px;
//   }
//   label {
//     display: inherit;
//     line-height: 32px;
//     &::after {
//       content: '';
//     }
//   }
// }
// :deep(.ant-form-item-control){
//   &::before {
//     content: ':';
//     display: inline-block;
//   }
// }
</style>
